import { _decorator, Component, director, EventTouch, Input, Node, tween, UITransform, Vec3 } from 'cc';
import { AudioManger } from './AudioManger';
import { Clips, events } from './Enums';
import { Global } from './Global';
import { PinAction } from './PinAction';
import { Tools } from './Tools';
const { ccclass, property } = _decorator;

@ccclass('EmptyHoleAction')
export class EmptyHoleAction extends Component {
    @property({ type: Node })
    lock: Node = null!;

    defalut_lock: boolean = false; // 默认锁状态
    isLocked: boolean = false;

    onLoad() {
        this.defalut_lock = this.lock?.active ?? false;
    }

    start() {
        // 需要时可开启触摸监听
        // this.node.on(Input.EventType.TOUCH_START, this.unlock_hole, this);
    }

    /** 设置锁显示与缩放动画 */
    set_lock_unlock(lock: boolean) {
        this.isLocked = lock;
        if (this.lock) {
            tween(this.lock)
                .to(0.25, { scale: new Vec3(1.2, 1.2, 1) }, Global.our_easing)
                .to(0.45, { scale: new Vec3(0.8, 0.8, 1) }, Global.our_easing)
                .to(0.25, { scale: new Vec3(1, 1, 1) }, Global.our_easing)
                .call(() => {
                    this.lock.scale = new Vec3(1, 1, 1);
                    this.lock.active = lock;
                })
                .start();
        }
    }

    /** 初始化状态，恢复默认锁和清理钉子 */
    init_empty_hole() {
        this.set_lock_unlock(this.defalut_lock);
        this.clear_pins();
    }

    /** 触摸解锁事件 */
    unlock_hole(e: EventTouch) {
        if (!this.isLocked) return;
        this.set_lock_unlock(false);
    }

    update(deltaTime: number) {
        // 空实现，如需逻辑可填充
    }

    /** 获取所有钉子PinAction数组 */
    public get_pin_arr(arr: PinAction[] = []): PinAction[] {
        this.node.children.forEach(child => {
            const pin = child.getComponent(PinAction);
            if (pin) arr.push(pin);
        });
        return arr;
    }

    /** 根据颜色ID获取未飞行状态的钉子 */
    public get_pin_arr_by_color_id(color_id: number, pin_arr: PinAction[]) {
        this.node.children.forEach(child => {
            const pin = child.getComponent(PinAction);
            if (pin && pin.pin_color?.id === color_id && !pin.is_flying()) {
                pin_arr.push(pin);
            }
        });
    }

    /** 判断是否能放钉子，当前无钉子则返回位置，否则返回null */
    private get_temp_position(): Vec3 | null {
        const pins = this.get_pin_arr();
        if (pins.length > 0) return null;
        return Vec3.ZERO.clone();
    }

    /** 清除所有钉子 */
    private clear_pins() {
        Tools.clearFromParent(this.node, PinAction);
    }

    /** 是否可放置钉子（未锁且无钉子） */
    public can_able_put(): boolean {
        if (this.isLocked) return false;
        return this.get_temp_position() !== null;
    }

    /** 放置钉子，带动画 */
    public put_pin(pin: PinAction): boolean {
        const targetHolePos = this.get_temp_position();
        if (!targetHolePos) return false;

        const worldPos = pin.node.getWorldPosition();
        const localPos = this.node.getComponent(UITransform).convertToNodeSpaceAR(worldPos);

        pin.set_flying(true);
        this.node.addChild(pin.node);
        pin.node.setPosition(localPos);
        pin.remove_collider();

        this.tween_play(pin, targetHolePos);
        return true;
    }

    /** 钉子飞行动画 */
    async tween_play(pin: PinAction, targetHolePos: Vec3) {
        const startPos = pin.node.position.clone();
        const lerpPos = startPos.lerp(targetHolePos, 0.1);

        tween(pin.node)
            .to(0.2, { scale: new Vec3(2, 2, 1), position: lerpPos, angle: 360 }, { easing: 'quadInOut' })
            .to(0.25, { position: targetHolePos }, { easing: 'quadInOut' })
            .call(() => {
                if (pin.pos_hole) pin.pos_hole.hide();
                pin.set_flying(false);
                director.emit(events.check_empty_hole, pin);
            })
            .to(0.2, { scale: Vec3.ONE }, { easing: 'quadInOut' })
            .start();
    }
}
